import * as lib from '../../../../components/aotoo/lib/index'
import { daystamp, today } from './today'
import { setPanReciprocal, emptyRecentReciprocal, getRecentReciprocal} from './recentreciprocal'
import {blueCards} from './bluecards'
import {shareTrigger} from './share/index'
import { announcePop } from './version'
import { caseButtons } from './casebuttons'

import { getCloudUser, getCloudFiles } from '../../common/cloud/index'
import {casePrefix, getCaseIdByName} from '../../funcs/index'
import {templateUrl} from '../../../../common/jscloud/index'

const commonHooks = lib.hooks('calender-announce', true)

function random(min, max) {
  if (arguments.length === 2) {
    return Math.floor(min + Math.random() * ((max + 1) - min))
  }
}

export {
  daystamp,
  today,
  emptyRecentReciprocal,
  setPanReciprocal,
  announcePop
}

const app = getApp();
const dateInfoHooks = lib.hooks('date-info', true)
const recentReciprocal = getRecentReciprocal()
const namespaceOfShareHooks = app.globalData.namespaceOfShareHooks


/**
 * 设置统计列表，统计标签按钮
 */
export function setCaseStatistics(ctx){
  const caseStatistics = dateInfoHooks.getItem('case-statistics')
  const $datas = Object.entries(caseStatistics).map(([caseKey, value])=>{
    value.caseKey = caseKey
    return value
  })

  if (ctx) {
    caseButtons(ctx, $datas)
  }
}


/**
 * 最近的倒数日记录
 * @returns 
 */
function rightRecentReciprocal(){
  const id = getCaseIdByName('reciprocal') || 22
  const bodys = recentReciprocal ? [
    ""+recentReciprocal.targetDay.diffDays,
    lib.subcontent((recentReciprocal.body[2]||'未填写'), 8, true),
    '倒数日'
  ] : [
    ' ',
    {title: '倒数日', attr: {type: id}, aim: 'onCase', itemStyle: 'margin-top: -2em; padding-top: 2em'}
  ]

  let itClass = ''
  if (bodys[0] === ' ') {
    itClass = ' invalid'
  }

  return {
    $$id: 'date-info-reciprocal',
    itemClass: 'date-func number reciprocal' + itClass,
    body: bodys,
  }
}


/**
 * 创建看板, 头图
 * @returns 
 */
export function mkDateInfo(){
  const defaultBg = dateInfoHooks.getItem('bg-img')
  const bgsrc = defaultBg ? defaultBg : ''
  return {
    itemClass: 'date-info',
    footerClass: 'date-info-footer',
    loading: bgsrc ? true : false,
    img: {src: bgsrc, mode: 'aspectFill', preview: true, itemStyle: 'width: 100%; height: 100%;'},
    // '@item': {
    //   $$id: 'date-info',
    //   itemClass: 'date-detail',
    //   title: ' ',
    //   "@md": {
    //     content: ' '
    //   }
    // },

    dot: [
      {
        itemClass: 'date-funcs',
        "@list": {
          type: {
            is: 'scroll',
            'scroll-y': false,
            'scroll-x': true,
            "enable-flex": true,
            "enhanced": true,
            "binddragstart": 'onDropButtonHideOptionFromPageIndex'
          },
          data: [
            ...blueCards({today}),

            // 最近能放假的节日
            // recentVaction(),

            // 最近的倒数日
            rightRecentReciprocal()
          ]
        }
      },


      // side-tool 工具栏
      {
        itemClass: 'iconfont date-toolbar',
        dot: [
          {itemClass: 'date-toolbar-refresh', aim: 'changeBg', title: '背景'},
          {itemClass: 'date-toolbar-message', aim: 'onMessage', title: '@分享'} // 分享消息
        ]
      },

      {
        $$id: 'share-info-button',
        itemClass: 'iconfont share-info-button',
        show: false,
        aim(){
          lib.tik()
          this.activePage.shareModal()
        },
        ready(){
          const acceptShareInfos = commonHooks.getItem(namespaceOfShareHooks)
          if (acceptShareInfos && acceptShareInfos.data.length) {
            const len = acceptShareInfos.data.length
            this.update({
              show: true,
              title: (len+'')
            })
          }
        }
      }
    ],

    methods: {
      onMessage(e){
        lib.tik()
        const activePage = this.activePage
        const today = activePage.today
        let   tapDay = {...activePage.tapDay}

        const doShare = (userInfo) => {
          shareTrigger({today, tapDay, userInfo})
        }

        let   userInfo = app.globalData.userInfo || commonHooks.getItem('user-info')
        const userProfile = app.globalData.userProfile||{}

        if (tapDay.timestamp < today.timestamp) {
          wx.showToast({title: '选择大于今天的日期再分享', icon: 'none'})
          return
        }

        if (!userInfo) {
          userInfo = userProfile
          wx.getUserProfile({
            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            fail(err){
              // console.log(err);
              doShare(userInfo)
            },
            success(res){
              // avatarUrl
              // country
              // city
              // gender
              // nickName
              // province
              userInfo = {...res.userInfo, ...userProfile}
              app.globalData.userInfo = userInfo
              commonHooks.setItem('user-info', userInfo)
              doShare(userInfo)
            }
          })
        } else {
          if (!userInfo.UID) {
            userInfo = {...userInfo, ...userProfile}
            app.globalData.userInfo = userInfo
            commonHooks.setItem('user-info', userInfo)
          }
          doShare(userInfo)
        }
      },

      changeBg(){
        lib.tik()
        this.updateBgImage()
      },

      updateBgImage(imgData, index=0){
        this.loading(true)
        const that = this
        imgData = this.images
        if (imgData.length >= 1) {
          if (this.selectBgIndex === undefined) {
            this.selectBgIndex = 0
          } else {
            this.selectBgIndex++
          }
          if(imgData[this.selectBgIndex] && bgsrc === imgData[this.selectBgIndex].src) {
            this.selectBgIndex++
          }
          if (this.selectBgIndex > (imgData.length-1)) {
            this.selectBgIndex = 0
          }
          index = this.selectBgIndex

          // index = random(0, (imgData.length-1))
          // if (this.selectBgIndex === index) {
          //   return this.updateBgImage(imgData)
          // } else if(bgsrc === imgData[index].src) {
          //   return this.updateBgImage(imgData)
          // }
          // else {
          //   this.selectBgIndex = index
          // }
        }
        dateInfoHooks.setItem('bg-img', imgData[index].src)
        this.update({ "img.src": imgData[index].src}, function(){
          setTimeout(() => {
            that.loading(false)
          }, 1000);
        })
      }
    },
    created(){
      this.images = [{src: '/images/bg.jpg'}]
      !app.globalData.userProfile && getCloudUser().then(profile=>{
        app.globalData.userProfile = profile
      })

      getCloudFiles({dir: 'bg/'}).then(res=>{
        this.images = this.images.concat(res.map(item=>({src: item})))
      })
    },
    attached(){
      !defaultBg && this.loading(true)
    },
    ready(){
      // setCaseStatistics(this.activePage)

      if (bgsrc) {
        setTimeout(() => {
          this.loading(false)
        }, 600);
      }
      
      if (!this.images) {
        templateUrl([
          'cloud://one-a9twq.6f6e-one-a9twq-1300765390/bg/bg.jpg',
          'cloud://one-a9twq.6f6e-one-a9twq-1300765390/bg/bg1.jpg',
        ]).then( res => {
          this.images = res.fileList.map(file=>({src: file.tempFileURL}))
          this.images.unshift({src: '/images/bg.jpg'})
          !defaultBg && this.updateBgImage(this.images)
        })
      } else {
        !defaultBg && this.updateBgImage(this.images)
      }
    },
  }
}
